package com.qili.core.quartz.CustomQuartz;

import cn.hutool.core.util.IdUtil;
import com.qili.entity.supervisor.SupervisorFileSjktj;
import com.qili.entity.supervisor.dto.SupervisorFileDTO;
import com.qili.entity.supervisor.dto.SupervisorFileSjktjDTO;
import com.qili.service.supervisor.SupervisorFileService;
import com.qili.service.supervisor.SupervisorFileSjktjService;
import lombok.extern.java.Log;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author zhaoyongke
 * @date 2022/5/14
 * @description
 */
@Log
public class ZjsjkFileListUpdateJob implements Job {


    @Autowired
    SupervisorFileSjktjService supervisorFileSjktjService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        log.info("==============================ZjsjkFileListUpdateJob：启动任务=======================");
        run();
        log.info("ZjsjkFileListUpdateJob：下次执行时间=====" +
                new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
                        .format(context.getNextFireTime()) + "==============");
    }

    public void run() {

        log.info("ZjsjkFileListUpdateJob=======开始==================================");
        String lockkey = "zjsjkData_key";
        String uuId = IdUtil.simpleUUID();
        try {
            lock(lockkey, uuId);
            //定时查询file表中的一部分数据更新到SupervisorFileSjktj
            //(1) 清空SupervisorFileSjktj
            SupervisorFileSjktj sfile = new SupervisorFileSjktj();
            int delete = supervisorFileSjktjService.delete(sfile);
            log.info("ZjsjkFileListUpdateJob=======共====="+delete+"=============================");
            log.info("ZjsjkFileListUpdateJob=======删除成功==================================");
            SupervisorFileSjktjDTO supervisorFileDTO = new SupervisorFileSjktjDTO();
            List<SupervisorFileSjktj> fileSjktjDTOList = supervisorFileSjktjService.queryZjsjkFile(supervisorFileDTO);
            int i = supervisorFileSjktjService.insertList(fileSjktjDTOList);
            log.info("ZjsjkFileListUpdateJob=======插入结束,插入了"+i+"条==================================");
        } catch (Exception e) {
            log.info("ZjsjkFileListUpdateJob=======出现异常了==================================");
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } finally {
            log.info("ZjsjkFileListUpdateJob=======释放锁==================================");
            unlock(lockkey, uuId);
        }


    }

    public void lock(String key, String uuId) {
        for (; ; ) {
            boolean r = stringRedisTemplate.opsForValue().setIfAbsent(key, uuId);
            stringRedisTemplate.expire(key, 600, TimeUnit.SECONDS);

            if (r) {
                return;
            } else {
                throw new RuntimeException("已经存在的执行程序...");
            }
        }
    }

    public void unlock(String key, String uuId) {
        if (uuId.equals(stringRedisTemplate.opsForValue().get(key))) {
            stringRedisTemplate.delete(key);
        }
    }
}
